package util;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Bowen on 2014/10/27.
 */
public class StringUtil {
    /** 8 位 UCS 转换格式     */
    public static final String UTF_8 = "UTF-8";
    /** 中文超大字符集     **/
    public static final String GBK = "GBK";

    /**
     * 按指定编码方式转换字符串
     * @param str 字符串
     * @param newCharset 编码方式
     * @return
     * @throws java.io.UnsupportedEncodingException
     */
    public static String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
        if(str != null) {
            byte[] bs = str.getBytes();
            //用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return null;
    }

    /**
     * 去掉字符串中转义字符
     * @param str 字符串
     * @return
     * @throws java.io.UnsupportedEncodingException
     */
    public static String specialFormat(String str) throws UnsupportedEncodingException {
        if(str != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            return m.replaceAll("");
        }
        return null;
    }

    public static boolean isEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查指定的字符串列表是否不为空。
     */
    public static boolean areNotEmpty(String... values) {
        boolean result = true;
        if (values == null || values.length == 0) {
            result = false;
        } else {
            for (String value : values) {
                result &= !isEmpty(value);
            }
        }
        return result;
    }

    //去掉首尾为空的字符
    public static String stringTrim(String value) {
        if(!isEmpty(value))
            return value.trim();
        else
            return value;
    }


    public static boolean isNullOrEmpty(String inStr) {
        return (inStr == null || inStr.trim().length() == 0);
    }
}
